package com.me.TextMissed_a1;


import java.util.Locale;

import com.me.TextMissed_a1.MyAppWidget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.net.Uri;
import android.provider.CallLog;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MyAppWidget extends AppWidgetProvider {
	
	private Toast toast;	
	public static final String UPDATE_ONDEMAND = "com.me.TextMissed_a1.UPDATE_ONDEMAND";
	public static final String UPDATE_PREFERENCE = "com.me.TextMissed_a1.UPDATE_PREFERENCE";
	
	private static String myTextSMS = null;
	private static String myTextCall = null;
	
	private static final String UNREAD_CONDITION = "read=0";
	private static final String SMSMMS_ID = "_id";
	private static final Uri SMS_CONTENT_URI = Uri.parse("content://sms");
	private static final Uri SMS_INBOX_CONTENT_URI = Uri.withAppendedPath(SMS_CONTENT_URI, "inbox");
	
	//load preferences			
	private static Boolean noneAlternative = true, enableMsg = true, enablePhn = true;
	
	private static int sizeMsg = 10 ,sizePhn = 10;
	private static int sizeMsgNumber = 12, sizePhnNumber = 12;
	private static int keyColorMsg = 0xffffffff, keyColorPhn = 0xffffffff;
	private static int keyColorMsgNumber = 0xffffffff, keyColorPhnNumber = 0xffffffff;
	private static int keyColorMsgNumberNonZero = 0xffffffff, keyColorPhnNumberNonZero = 0xffffffff;
	

	
	//Automatic updater
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onUpdate ");
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		
		//get configuration language
		Configuration config = context.getResources().getConfiguration();
		Locale.getDefault();
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onUpdate Configuration config AFTER: "+config.locale);
		
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			//Update layout
			updateWidgetLayout(views, context,appWidgetId);			
	        
			 // Klik do otwarcia wiadomosci sms
	        Intent intent = new Intent();
	        intent.setAction(WidgetReceiver.WIDGET_INTENT_SMS);
	        intent.setClassName(WidgetReceiver.class.getPackage().getName(), WidgetReceiver.class.getName());
	        PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	        views.setOnClickPendingIntent(R.id.tvWidgetText1, pendingIntent);
	        views.setOnClickPendingIntent(R.id.tvWidgetText2, pendingIntent);	        

	        // Klik do otwarcia rejestru nie odebranych polaczen
	        intent.setAction(WidgetReceiver.WIDGET_INTENT_CALL);
	        intent.setClassName(WidgetReceiver.class.getPackage().getName(), WidgetReceiver.class.getName());
	        PendingIntent pendingIntentCall = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	        views.setOnClickPendingIntent(R.id.tvWidgetText3, pendingIntentCall);
	        views.setOnClickPendingIntent(R.id.tvWidgetText4, pendingIntentCall);			
			
			//update widget
			appWidgetManager.updateAppWidget(appWidgetId, views);	
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onReceive ");
		super.onReceive(context, intent);		
		
		//get unread sms
		myTextSMS = String.valueOf(getUnreadSmsCount(context));
        
        //get missed calls
        myTextCall = String.valueOf(getMissedPhoneCalls(context));
		
        //update on timer ???????????????????????????????????????
        if(intent.getAction().equals(UPDATE_ONDEMAND)) {
			updateWidget(context);
			Log.d("_TextMissed_a1_", "Widget onReceive SMS: "+ myTextSMS+" Call: "+ myTextCall);			
		}
		
		//update preference
		if(intent.getAction().equals(UPDATE_PREFERENCE)) { 
			updateWidgetLanguage(context);
		}
	}	
	
	//On demand language updater
	public void updateWidgetLanguage(Context context) {
		//get configuration language
		Locale.getDefault();		
				
		//Get AppWidgetManager
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		//Get widget IDs
		ComponentName thisWidged = new ComponentName(context, MyAppWidget.class);
		int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidged);
		//Update all widget copies
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			//Update layout
			updateWidgetLayout(views, context, appWidgetId);
			//Save changes
			appWidgetManager.updateAppWidget(appWidgetId, views);
		}		
	}
	
	//load parameters of widget
	private void loadPreferences(Context context, int appWidgetId) {
		Log.d("_TextMissed_a1_", "loadPreferences ");
		String[] parameters = AppWidgetConfigure.getParameters(context, appWidgetId);
		noneAlternative = Boolean.parseBoolean(parameters[0]);
		enableMsg = Boolean.parseBoolean(parameters[1]);
		enablePhn = Boolean.parseBoolean(parameters[8]);
		
		if (parameters[3] != "null") sizeMsg= Integer.parseInt(parameters[3]); 
		if (parameters[4] != "null") sizeMsgNumber = Integer.parseInt(parameters[4]);
		if (parameters[5] != "null") keyColorMsg = Integer.parseInt(parameters[5]);
		if (parameters[6] != "null") keyColorMsgNumber = Integer.parseInt(parameters[6]);		
		if (parameters[7] != "null") keyColorMsgNumberNonZero = Integer.parseInt(parameters[7]);
		if (parameters[9] != "null") sizePhn = Integer.parseInt(parameters[9]);
		if (parameters[10] != "null") sizePhnNumber = Integer.parseInt(parameters[10]);
		if (parameters[11] != "null") keyColorPhn = Integer.parseInt(parameters[11]);
		if (parameters[12] != "null") keyColorPhnNumber = Integer.parseInt(parameters[12]);		
		if (parameters[13] != "null") keyColorPhnNumberNonZero = Integer.parseInt(parameters[13]);
	}
	
	//updateWidgetLayout after changes
	private void updateWidgetLayout(RemoteViews views, Context context, int appWidgetId){
		//views.setTextViewText(R.id.tvWidgetText1, context.getString(R.string.tvWidgetText1));		
		//views.setTextViewText(R.id.tvWidgetText3, context.getString(R.string.tvWidgetText3));		
		
		//load preferences
		loadPreferences(context, appWidgetId);

		Log.d("_TextMissed_a1_", "updateWidgetLayout enableMsg "+ enableMsg+"  enablePhn: "+enablePhn);
		Log.d("_TextMissed_a1_", "updateWidgetLayout CALL sizePhn: "+sizePhn+" sizePhnNumber: "+sizePhnNumber+" keyColorPhnNumber: "+ keyColorPhnNumber+"  keyColorPhnNumberNonZero: "+keyColorPhnNumberNonZero +" myTextSMS: "+myTextSMS);
		
		if (enableMsg) {	//dla SMS-ow								
			updateTextValue(sizeMsg, views, R.id.tvWidgetText1, context, context.getString(R.string.tvWidgetText1),keyColorMsg);
			views.setViewVisibility(R.id.tvWidgetText1, View.VISIBLE); //View.VISIBLE
			
			int numberColor = keyColorMsgNumberNonZero;
			
			if (myTextSMS == null || myTextSMS=="0") { 
				myTextSMS = "0";
				numberColor = keyColorMsgNumber;
			}
			String textSMS = myTextSMS;
			
			//0 is zero
			if (noneAlternative) {
				textSMS = findStringIdinArrayXML(myTextSMS, context);
				//textCall = findStringIdinArrayXML(myTextCall, context);
			} 
			
			//aktualizacja ilosc sms widgetu
			updateNumberValue(sizeMsgNumber, textSMS, views, R.id.tvWidgetText2, numberColor);
			views.setViewVisibility(R.id.tvWidgetText2, View.VISIBLE); //View.VISIBLE
			
			//updateNumberValue(sizeMsgNumber, textCall, views, R.id.tvWidgetText4);
			//views.setViewVisibility(R.id.tvWidgetText4, View.VISIBLE); //View.VISIBLE
			
		} else {
			views.setViewVisibility(R.id.tvWidgetText1, View.GONE); //View.VISIBLE
			views.setViewVisibility(R.id.tvWidgetText2, View.GONE); //View.VISIBLE
		}
		
		//dla polaczen telefonicznych
		if (enablePhn) {									
			updateTextValue(sizePhn, views, R.id.tvWidgetText3, context, context.getString(R.string.tvWidgetText3),keyColorPhn);
			
			int numberPhnColor = keyColorPhnNumberNonZero;
			//update calls numbers
			if (myTextCall == null || myTextCall=="0") {
				myTextCall = "0";
				numberPhnColor = keyColorPhnNumber;
			}
			String textCall = myTextCall;
			
			//0 is zero
			if (noneAlternative) {
				textCall = findStringIdinArrayXML(myTextCall, context);
			} 
			
			//aktualizacja ilosc rozmow telefinicznych widgetu
			updateNumberValue(sizePhnNumber, textCall, views, R.id.tvWidgetText4, numberPhnColor);			
			
			views.setViewVisibility(R.id.tvWidgetText3, View.VISIBLE); //View.VISIBLE
			views.setViewVisibility(R.id.tvWidgetText4, View.VISIBLE); //View.VISIBLE
		} else {
			views.setViewVisibility(R.id.tvWidgetText3, View.GONE); //View.VISIBLE
			views.setViewVisibility(R.id.tvWidgetText4, View.GONE); //View.VISIBLE
		}
		//Log.d("_TextMissed_a1_", "updateWidgetLayout SMS "+ myTextSMS+"  enableMsg: "+parameters[1]+" sizeMsgNumber:"+sizeMsgNumber);		
	}
	
	//update text value of widget
	private void updateTextValue(int sizeMsg, RemoteViews views, int viewId, Context context, String text, int keyColorMsg) {		
		//String text = context.getString(viewId); 		 
        Paint  mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(sizeMsg);
        mPaint.setColor(keyColorMsg);
        //mPaint.setColor(color);
        mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));
        float textWidth = mPaint.measureText(text, 0, text.length());
        int bitmapWidth = (int) textWidth;
        // Create an empty, mutable bitmap
		Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, sizeMsg+15, Bitmap.Config.ARGB_4444);
		// get a canvas to paint over the bitmap
		Canvas canvas = new Canvas(bitmap);
		bitmap.eraseColor(0);	

		//test
		Paint  mPaint1 = new Paint();
		mPaint1.setColor(0xff666666);
		canvas.drawRect(0, 0, bitmapWidth, sizeMsg+5, mPaint1);
		//test
		
		canvas.drawText(text, 0,15, mPaint);		
		views.setImageViewBitmap(viewId, bitmap);
		//Log.d("_TextMissed_a1_", "updateTextValue text "+ text+"  id: "+viewId+" sizeMsg:"+sizeMsg+" text: "+text);
	}
	
	//update number value of widget
	private void updateNumberValue(int sizeMsgNumber, String textSMS, RemoteViews views, int viewId ,int numberColor) {
		//text = context.getString(R.string.tvWidgetText2); 		 
		Paint  mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(sizeMsgNumber);
        mPaint.setColor(numberColor);
        mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD));
        float textWidth = mPaint.measureText(textSMS, 0, textSMS.length());
        int bitmapWidth = (int) textWidth;
        // Create an empty, mutable bitmap
		Bitmap bitmap = Bitmap.createBitmap( bitmapWidth, sizeMsgNumber+18, Bitmap.Config.ARGB_4444);
		// get a canvas to paint over the bitmap
		Canvas canvas = new Canvas(bitmap);
		bitmap.eraseColor(0);
		
		//test
		Paint  mPaint1 = new Paint();
		mPaint1.setColor(0xff000000);
		canvas.drawRect(0, 0, bitmapWidth, sizeMsgNumber+8, mPaint1);
		//test
		
		canvas.drawText(textSMS, 0,18, mPaint);		
		views.setImageViewBitmap(viewId, bitmap);
	}
	
	//On demand updater
	private void updateWidget(Context context) { //, String myTextSMS, String myTextCall) { //myTextSMS, myTextCall
		//get configuration language
		Locale.getDefault();
		
		//Get AppWidgetManager
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		//Get widget IDs
		ComponentName thisWidged = new ComponentName(context, MyAppWidget.class);
		int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidged);
		//Update all widget copies
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			//load preferences
			loadPreferences(context, appWidgetId);
			
			int numberColor = keyColorMsgNumberNonZero;
			
			//update sms numbers
			if (myTextSMS == null || myTextSMS=="0") { 
				myTextSMS = "0";
				numberColor = keyColorMsgNumber;
			}
			String textSMS = myTextSMS;
			
			int numberPhnColor = keyColorPhnNumberNonZero;
			//update calls numbers
			if (myTextCall == null || myTextCall=="0") {
				myTextCall = "0";
				numberPhnColor = keyColorPhnNumber;
			}
			String textCall = myTextCall;
			
			//0 is zero
			if (noneAlternative) {
				textSMS = findStringIdinArrayXML(myTextSMS, context);
				textCall = findStringIdinArrayXML(myTextCall, context);
			} 
			
			updateNumberValue(sizeMsgNumber, textSMS, views, R.id.tvWidgetText2,numberColor );
			updateNumberValue(sizePhnNumber, textCall, views, R.id.tvWidgetText4,numberPhnColor );
						
			//Save changes
			appWidgetManager.updateAppWidget(appWidgetId, views);
			
			Log.d("_TextMissed_a1_", "Widget updateWidget");		
		}
	}
	
	//zamien string na id w tablicy strings.xml
	private String findStringIdinArrayXML(String find, Context context) {
		String smsNumber="";
		String nmbToFind = "number00"+find;
		if (Integer.parseInt(find) == 0)
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		else if (Integer.parseInt(find) > 0 && Integer.parseInt(find) < 10 )
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		else if (Integer.parseInt(find) >= 10 && Integer.parseInt(find) < 100 ){
			nmbToFind = "number0"+find;
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		}
		else 
			smsNumber = find;
		
		return smsNumber;
	}
	
	@Override
	public void onDisabled(Context context) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onDisabled ");
		// TODO Auto-generated method stub
		super.onDisabled(context);
		
		//start service 
		context.stopService(new Intent(context, MyService.class));
	}

	@Override
	public void onEnabled(Context context) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onEnabled ");
		// TODO Auto-generated method stub
		super.onEnabled(context);
		
		//start service 
		context.startService(new Intent(context, MyService.class));
	}
    
    //showToast
    public void showToast(String text) {
        toast.setText(text);
        toast.show();
    }
	
	/**
	 * Return current unread message count from system db (sms only)
	 * 
	 * @param context
	 * @return unread sms message count
	 */
	private static int getUnreadSmsCount(Context context) {

		final String[] projection = new String[] { SMSMMS_ID };
		final String selection = UNREAD_CONDITION;
		final String[] selectionArgs = null;
		final String sortOrder = null;

		int count = 0;

		Cursor cursor = context.getContentResolver().query(
				SMS_INBOX_CONTENT_URI, projection, selection, selectionArgs,
				sortOrder);

		if (cursor != null) {
			try {
				count = cursor.getCount();
			} finally {
				cursor.close();
			}
		}

		Log.d("_TextMissed_a1_", "sms unread count = " + count);
		return count;
	}

	
	/**
	 * Return the number of missed phone calls
	 * 
	 * @param context
	 * @return missed phone calls
	 */
	synchronized private static int getMissedPhoneCalls(Context context) {
		String queryString = CallLog.Calls.TYPE+"="+CallLog.Calls.MISSED_TYPE+" AND "+CallLog.Calls.NEW+"=1";;
		int ret = 0;
		Cursor c = context.getContentResolver().
			query(CallLog.Calls.CONTENT_URI, new String[]{"_id"}, 
					queryString, null, null);
		if (c != null) {
			try {
				if (c.moveToNext()) {
					ret= c.getCount();
				}
			} finally {
				c.close();
			}
		}
		Log.d("_TextMissed_a1_", "getMissedPhoneCalls: " + ret);
		return ret;
	}
}